package com.bakar.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bakar.service.UserService;
import com.bakar.util.BakarConstants;
import com.bakar.util.BakarUtils;
import com.bakar.valueobjects.UserVO;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		
		// Get the user from the User Service
		com.google.appengine.api.users.UserService googleUserService = UserServiceFactory.getUserService();
		User user = googleUserService.getCurrentUser();
		String loginId = null;
		
		//String loginId = req.getParameter("loginId"); // just for development purpose
		// If user is not present then send him to the login page
		if (user != null && user.getUserId() != null )	loginId = BakarUtils.getLoginId(user);
		if (loginId != null ){
			UserVO userVO = new UserVO();
			
			userVO.setLoginId(loginId);
			UserVO userFrmDB = UserService.getUser(userVO);
			
			// If the user is login for the first time then create 
			// its entry in the database
			if (userFrmDB==null){
				userVO.setStatus(BakarConstants.STATUS_AVAILABLE);
				userVO.setDisplayName(loginId);
				userVO.setImagePath("no_image_m.png");
				UserService.saveUser(userVO);
			} else {
				// Just update its status to Available
				userFrmDB.setStatus(BakarConstants.STATUS_AVAILABLE);
				UserService.updateStatus(userFrmDB);
			}
			
			String imagePath = null;
			req.setAttribute("currentUser", loginId.toLowerCase());
			if (userFrmDB == null || userFrmDB.getImagePath() == null || "".equals(userFrmDB.getImagePath().trim())){
				imagePath ="no_image_m.png";
			} else {
				imagePath = userFrmDB.getImagePath();
			}
			req.setAttribute("currentUserImage", imagePath);
			if (userFrmDB != null){
				req.setAttribute("localuserdisplayname", userFrmDB.getDisplayName());
			}			
			req.getRequestDispatcher("chat.jsp").forward(req, resp);
		} else {
			// User has bot logged in send him to login
			((HttpServletResponse)resp).sendRedirect(googleUserService.createLoginURL(((HttpServletRequest)req).getRequestURI())); 
		}
		
		}
		
	
}
